﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.Hosting;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using LP580.CG;

/// <summary>
///Utils 的摘要说明
/// </summary>
public class Utils
{
    /// <summary>
    /// 密钥
    /// </summary>
    private static string enKey = "F5F5###5";

    public Utils()
    {

    }


    public static string preSaveDB(string oldStr)
    {
        string tmp = oldStr.Replace("'", "''");
        tmp = tmp.Replace("%", "");
        //tmp = oldStr.Replace("_", "");
        tmp = NoHTML(tmp);
        return tmp;
    }

    public static string preSaveDB(string oldStr,int maxLen)
    {
        string tmp = "";
        if (oldStr.Length > maxLen)
        {
            tmp = oldStr.Substring(0, maxLen);
        }
        else
        {
            tmp = oldStr;
        }
        tmp = preSaveDB(tmp);
        return tmp;
    }


    public static void GobalRun()
    {
        getCookieUser();
    }

    public static string aftReadDB(string newStr)
    {
        string tmp = newStr.Replace("<br />", "\n");
        return tmp;
    }

    public static int RQ_int(string key)
    {
        return StrToNum(HttpContext.Current.Request.QueryString[key]);
    }

    public static string RQ_str(string key)
    {
        string v;
        if (HttpContext.Current.Request.QueryString[key] == null)
            v = "";
        else
            v = HttpContext.Current.Request.QueryString[key].ToString();
        return v;
    }

    public static int RF_int(string key)
    {
        return StrToNum(HttpContext.Current.Request.Form[key]);
    }

    public static string RF_str(string key)
    {
        string v;
        if (HttpContext.Current.Request.Form[key] == null)
            v = "";
        else
            v = HttpContext.Current.Request.Form[key].ToString();
        return CheckSqlStr(v);
    }
    /// <summary>
    /// 过滤sql字符串
    /// </summary>
    /// <param name="tStr"></param>
    /// <returns></returns>
    public static string CheckSqlStr(string tStr)
    {
        if (tStr == null)
        {
            return "";
        }
        else
        {
            string tmp1;
            string tmp = tStr.Replace("'", "&#39;").Replace(";", "&#59;");
            tmp1 = tmp.ToLower();
            if (tmp1.IndexOf("cast") > 0)
            {
                tStr = tmp1.Replace("cast", "&#99;ast");
            }
            else
            {
                tStr = tmp.Trim();
            }
            return tStr;
        }
    }
    /// <summary>
    /// 检查字符串是否为数值
    /// </summary>
    /// <param name="tStr"></param>
    /// <returns></returns>
    public static bool CheckNum(string tStr)
    {
        if (tStr == null) return false;
        foreach (char t in tStr)
        {
            if (t < '0' || t > '9')
            {
                return false;
            }
        }
        return true;
    }
    /// <summary>
    /// 将字符串转换为数值
    /// </summary>
    /// <param name="tStr"></param>
    /// <returns></returns>
    public static int StrToNum(string tStr)
    {
        if (CheckNum(tStr)) return Convert.ToInt32(tStr);
        return 0;
    }

    public static void WrAlertGoBack(string msg)
    {
        HttpContext.Current.Response.Write("<script>alert('" + msg + "');history.go(-1);</script>");
        HttpContext.Current.Response.End();
    }
    public static void WrAlertGo(string msg, string url)
    {
        HttpContext.Current.Response.Write("<script>alert('" + msg + "');document.location='" + url + "';</script>");
        HttpContext.Current.Response.End();
    }
    public static void WrAlert(string msg)
    {
        HttpContext.Current.Response.Write("<script>alert('" + msg + "');</script>");
    }

    public static void d(object v)
    {
        string s = string.Format("***************************<br />Value:{0}<br />Type:{1}<br />***************************", v, v.GetType());

        HttpContext.Current.Response.Write(s);
    }

    public static void de(object v)
    {
        string s = string.Format("***************************<br />Value:{0}<br />Type:{1}<br />***************************", v, v.GetType());
        HttpContext.Current.Response.Write(s);
        HttpContext.Current.Response.End();
    }

    /// <summary>
    /// 去除HTML标记
    /// </summary>
    /// <param name="Htmlstring"></param>
    /// <returns></returns>
    public static string NoHTML(string Htmlstring)
    {
        //删除脚本

        Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);

        //删除HTML

        Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(ldquo|#34);", "“", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(rdquo|#34);", "”", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(middot|#34);", "·", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

        Htmlstring.Replace("<", "");

        Htmlstring.Replace(">", "");

        Htmlstring.Replace("\r\n", "");

        Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

        return Htmlstring;

    }

    public static string matchImage(string str)
    {
        RegexOptions Optinos = RegexOptions.Singleline | RegexOptions.IgnoreCase;
        //Regex regex = new Regex("(?<=<img\\s*src=\"?)[^\"]+?(?=\"?>)", Optinos);
        Regex regex = new Regex("src\\=.+?\\.(gif|jpg|bmp|npg)", Optinos);
        //str = "<img   src=sdd.gif>";
        Match match = regex.Match(str);
        return (match.Success ? match.Value.ToString() : string.Empty.ToString());
    }

    public static string sampleContent(string str, int MaxLen)
    {
        string tmp = NoHTML(str);
        if (tmp.Length > MaxLen)
            tmp = tmp.Substring(0, MaxLen);
        return tmp;
    }

    public static string LimitTitle(string title, int MaxLen)
    {
        string rv;
        if (title.Length > MaxLen)
            rv = title.Substring(0, MaxLen - 2) + "..";
        else
            rv = title;
        return rv;
    }

    public static string FliterBadWords(string str)
    {
        string rv;
        rv = Regex.Replace(str, @"select", "", RegexOptions.IgnoreCase);
        return rv;
    }


    /**/
    /// <summary>
    /// 将Web站点下的绝对路径转换为相对于指定页面的虚拟路径
    /// </summary>
    /// <param name="page">当前页面指针，一般为this</param>
    /// <param name="specifiedPath">绝对路径</param>
    /// <returns>虚拟路径, 型如: ../../</returns>
    public static string ConvertSpecifiedPathToRelativePathForPage(Page page, string specifiedPath)
    {
        // 根目录虚拟路径
        string virtualPath = page.Request.ApplicationPath;
        // 根目录绝对路径
        string pathRooted = HostingEnvironment.MapPath(virtualPath);
        // 页面虚拟路径
        string pageVirtualPath = page.Request.Path;

        if (!Path.IsPathRooted(specifiedPath) || specifiedPath.IndexOf(pathRooted) == -1)
        {
            throw new Exception(string.Format("\"{0}\"是虚拟路径而不是绝对路径!", specifiedPath));
        }

        // 转换成相对路径 
        //(测试发现，pathRooted 在 VS2005 自带的服务器跟在IIS下根目录或者虚拟目录运行似乎不一样,
        // 有此地方后面会加"\", 有些则不会, 为保险起见判断一下)
        if (pathRooted.Substring(pathRooted.Length - 1, 1) == "\\")
        {
            specifiedPath = specifiedPath.Replace(pathRooted, "/");
        }
        else
        {
            specifiedPath = specifiedPath.Replace(pathRooted, "");
        }

        string relativePath = specifiedPath.Replace("\\", "/");

        string[] pageNodes = pageVirtualPath.Split('/');

        // 减去最后一个页面和前面一个 "" 值
        int pageNodesCount = pageNodes.Length - 2;


        for (int i = 0; i < pageNodesCount; i++)
        {
            relativePath = "/.." + relativePath;
        }

        if (pageNodesCount > 0)
        {
            // 如果存在 ".." , 则把最前面的 "/" 去掉
            relativePath = relativePath.Substring(1, relativePath.Length - 1);
        }

        return relativePath;
    }

    /// <summary>
    /// 读取模板文件
    /// </summary>
    /// <param name="filepath"></param>
    /// <returns></returns>
    public static string ReadHtmlTmp(string filepath)
    {
        System.Text.Encoding code = System.Text.Encoding.GetEncoding("gb2312");
        string temp = HttpContext.Current.Server.MapPath(filepath);
        StreamReader sr = null;
        string strRv = "";
        try
        {
            sr = new StreamReader(temp, code);
            strRv = sr.ReadToEnd();
            sr.Close();
        }
        catch (Exception exp)
        {
            HttpContext.Current.Response.Write(exp.Message);
            HttpContext.Current.Response.End();
        }
        return strRv;

    }

    public static string MakeRndName(string rootpath)
    {
        string rv = "";
        string NewDir = DateTime.Now.ToString("yyyy-MM-dd");

        if (!Directory.Exists(rootpath + "\\" + NewDir))
        {
            Directory.CreateDirectory(rootpath + "\\" + NewDir);
        }
        rv = NewDir + "/" + DateTime.Now.ToString("yyyyMMddhhmmss");
        return rv;
    }

    public static string getCookieUser()
    {
        clsUserAccount user = clsUserAccount.getCookieUser();
        string username = "";
        if (user == null)
        {
            HttpContext.Current.Response.Write("<script>alert('您尚未正常登陆或登陆已失效。\\n\\n请重新登陆，谢谢!');top.location='../Login.aspx';</script>");
            HttpContext.Current.Response.End();
        }
        else
        {
            username = user.UserName;
        }
        return username;
    }

    public static void saveCookies(string key, string value, DateTime dt)
    {
        HttpCookie myCookie = new HttpCookie(key);
        myCookie.Value = value;
        //myCookie[key] = value;
        myCookie.Expires = dt;
        HttpContext.Current.Response.Cookies.Add(myCookie);
    }

    public static string readCookies(string key)
    {
        string rv = "";
        if (HttpContext.Current.Request.Cookies[key] != null)
        {
            //if (HttpContext.Current.Request.Cookies["AGOA"][key] != null)
            //{
            rv = HttpContext.Current.Request.Cookies[key].Value;
            //}
        }
        return rv;
    }

    public static string Encrypt(string pToEncrypt)
    {
        string sKey = enKey;
        //访问数据加密标准(DES)算法的加密服务提供程序 (CSP) 版本的包装对象
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);　//建立加密对象的密钥和偏移量
        des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);　 //原文使用ASCIIEncoding.ASCII方法的GetBytes方法

        byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);//把字符串放到byte数组中

        MemoryStream ms = new MemoryStream();//创建其支持存储区为内存的流　
        //定义将数据流链接到加密转换的流
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        //上面已经完成了把加密后的结果放到内存中去

        StringBuilder ret = new StringBuilder();
        foreach (byte b in ms.ToArray())
        {
            ret.AppendFormat("{0:X2}", b);
        }
        ret.ToString();
        return ret.ToString();
    }

    /// <summary>
    /// DEC 解密过程
    /// </summary>
    /// <param name="pToDecrypt">被解密的字符串</param>
    /// <param name="sKey">密钥（只支持8个字节的密钥，同前面的加密密钥相同）</param>
    /// <returns>返回被解密的字符串</returns>
    public static string Decrypt(string pToDecrypt)
    {
        string sKey = enKey;
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();

        byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
        for (int x = 0; x < pToDecrypt.Length / 2; x++)
        {
            int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
            inputByteArray[x] = (byte)i;
        }

        des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);　//建立加密对象的密钥和偏移量，此值重要，不能修改
        des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();

        //建立StringBuild对象，createDecrypt使用的是流对象，必须把解密后的文本变成流对象
        StringBuilder ret = new StringBuilder();

        return System.Text.Encoding.Default.GetString(ms.ToArray());
    }

}
